package com.miso.common.file.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.miso.common.file.model.FileMeta;

 
@Controller
@RequestMapping("/controller")
public class FileController {
	@RequestMapping("/fileupload")  //어노테이션 설정 /main으로 url요청이 들어오면 이 컨트롤러로 매핑하겠단 뜻.
	public String cns0090 (
			Model model) {
System.out.println("====================================================1111");
Calendar c = Calendar.getInstance();

System.out.println("====================================================1111"+c.get(Calendar.DAY_OF_WEEK));
		return "/fileup";
	}
    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    FileMeta fileMeta = null;
    /***************************************************
     * URL: /rest/controller/upload  
     * upload(): receives files
     * @param request : MultipartHttpServletRequest auto passed
     * @param response : HttpServletResponse auto passed
     * @return LinkedList<FileMeta> as json format
     ****************************************************/
    @RequestMapping(value="/upload", method = RequestMethod.POST)
    public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {

System.out.println("====================================================2222");
        //1. build an iterator
         Iterator<String> itr =  request.getFileNames();
         MultipartFile mpf = null;
 
         //2. get each file
         while(itr.hasNext()){
 
             //2.1 get next MultipartFile
             mpf = request.getFile(itr.next()); 
             System.out.println(mpf.getOriginalFilename() +" uploaded! "+files.size());
 
             //2.2 if files > 10 remove the first from the list
             if(files.size() >= 10)
                 files.pop();
 
             //2.3 create new fileMeta
             fileMeta = new FileMeta();
             fileMeta.setFileName(mpf.getOriginalFilename());
             fileMeta.setFileSize(mpf.getSize()/1024+" Kb");
             fileMeta.setFileType(mpf.getContentType());
 
             try {
                fileMeta.setBytes(mpf.getBytes());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             //2.4 add to files
             files.add(fileMeta);
         }
        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
        return files;
    }
    /***************************************************
     * URL: /rest/controller/get/{value}
     * get(): get file as an attachment
     * @param response : passed by the server
     * @param value : value from the URL
     * @return void
     ****************************************************/
    @RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
     public void get(HttpServletResponse response,@PathVariable String value){
    	System.out.println("====================================================3333");
         FileMeta getFile = files.get(Integer.parseInt(value));
         try {      
                response.setContentType(getFile.getFileType());
                response.setHeader("Content-disposition", "attachment; filename=\""+getFile.getFileName()+"\"");
                FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
         }catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
         }
     }
    

    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
    @ResponseBody
    public List<FileMeta> upload(
        @RequestParam(value = "files[]", required = false) MultipartFile[] mfiles) throws IllegalStateException, IOException {

    	System.out.println("====================================================444444444");
      List<FileMeta> fileMetas = new ArrayList<FileMeta>();
  	System.out.println("====================================================444444443");
      for (MultipartFile file : mfiles) {
      	System.out.println("====================================================4444444442"+file.getOriginalFilename());
        //File uploadFile = new File("/home/hosting_users/codetwo/tomcat/file/",file.getOriginalFilename());
      	File uploadFile = new File("/",file.getOriginalFilename());
        file.transferTo(uploadFile);
        FileMeta fileMeta = new FileMeta(uploadFile.getAbsolutePath(), file.getSize()/1024+" Kb", "");
        files.add(fileMeta);
      }
     
      return files;
    }

}
